import { HomeAction, HomeType } from '@/types/store'

const initValue: HomeType = {
  userChannels: [],
  allChannels: [],
  active: 0,
  channelArticles: {},
}
export default function home(
  prevState = initValue,
  action: HomeAction
): HomeType {
  switch (action.type) {
    case 'home/getUserChannels':
      return {
        ...prevState,
        userChannels: action.payload,
      }
    case 'home/getAllChannels':
      return {
        ...prevState,
        allChannels: action.payload,
      }
    case 'home/changeActive':
      return {
        ...prevState,
        active: action.payload,
      }
    case 'home/saveChannelArticles': {
      const { channel_id, timestamp, articles } = action.payload
      const old = prevState.channelArticles[channel_id]?.articles || []
      return {
        ...prevState,
        channelArticles: {
          ...prevState.channelArticles,
          [channel_id]: {
            timestamp,
            articles: [...old, ...articles],
          },
        },
      }
    }
    case 'home/refreshChannelArticles': {
      const { channel_id, timestamp, articles } = action.payload
      const channelArticles = prevState.channelArticles
      return {
        ...prevState,
        channelArticles: {
          ...channelArticles,
          [channel_id]: {
            timestamp,
            articles: [...articles],
          },
        },
      }
    }
    default:
      return prevState
  }
}
